/**
 * created by uu, 16/07/15
 * #                                                   #
 * #                       _oo0oo_                     #
 * #                      o8888888o                    #
 * #                      88" . "88                    #
 * #                      (| -_- |)                    #
 * #                      0\  =  /0                    #
 * #                    ___/`---'\___                  #
 * #                  .' \\|     |# '.                 #
 * #                 / \\|||  :  |||# \                #
 * #                / _||||| -:- |||||- \              #
 * #               |   | \\\  -  #/ |   |              #
 * #               | \_|  ''\---/''  |_/ |             #
 * #               \  .-\__  '-'  ___/-. /             #
 * #             ___'. .'  /--.--\  `. .'___           #
 * #          ."" '<  `.___\_<|>_/___.' >' "".         #
 * #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
 * #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
 * #     =====`-.____`.___ \_____/___.-`___.-'=====    #
 * #                       `=---='                     #
 * #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
 * #                                                   #
 * #               佛祖保佑         永无BUG            #
 * #                                                   #
 */
package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.BlogSelectAdapter2;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.BlogType;
import com.hemaapp.yjnh.bean.CustomCount;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 田家的商品管理
 */
public class ManagerGoodsActivity extends BaseActivity {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_sale_count)
    TextView tvSaleCount;
    @Bind(R.id.tv_warehouse_count)
    TextView tvWarehouseCount;
    @Bind(R.id.listview)
    XtomListView listview;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout refreshLoadmoreLayout;
    @Bind(R.id.tv_manager)
    TextView tvManager;
    @Bind(R.id.ckbx_all)
    CheckBox ckbxAll;
    @Bind(R.id.layout_manager)
    RelativeLayout layoutManager;
    @Bind(R.id.line_sales)
    View lineSales;
    @Bind(R.id.line_warehouse)
    View lineWarehouse;
    @Bind(R.id.layout_sale)
    LinearLayout layoutSale;
    @Bind(R.id.tv_assort)
    TextView tvAssort;
    @Bind(R.id.tv_new)
    TextView tvNew;
    @Bind(R.id.tv_delete)
    TextView tvDelete;
    @Bind(R.id.tv_off_shelf)
    TextView tvOffShelf;
    @Bind(R.id.line_manager)
    View lineManager;

    private BlogSelectAdapter2 adapter;
    private ArrayList<Blog> mDatas = new ArrayList<>();
    private ArrayList<BlogType> types = new ArrayList<>();
    private int page = 0;
    private User user;
    private String keytype = "1";//类型	1销售中；0仓库中
    private PopupWindow mPopupWindow;
    private String typename = "";//分类名称
    private boolean isAllChecked = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_manager_customize);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        user = getApplicationContext().getUser();
        EventBus.getDefault().register(this);
        getNetWorker().getBlogTypeList("4", "0");
        getNetWorker().getCustomCount(user.getToken(), "2");
        getNetWorker().blogList("3", user.getId(), "5", "1", typename, keytype, "", "", "", "", "", "", "", "", page + "");
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void setListener() {
        titleText.setText("商品管理");
        titleRightBtn.setText("确定");
        tvNew.setText("发布");
        titleRightBtn.setVisibility(View.GONE);
//        ckbxAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                for (Blog blog : mDatas) {
//                    if (isChecked)
//                        blog.setCheck(true);
//                    else
//                        blog.setCheck(false);
//                }
//                adapter.notifyDataSetChanged();
//            }
//        });
        refreshLoadmoreLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page = 0;
                getNetWorker().getCustomCount(user.getToken(), "2");
                getNetWorker().blogList("3", user.getId(), "5", "1", typename, keytype, "", "", "", "", "", "", "", "", page + "");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page++;
                getNetWorker().blogList("3", user.getId(), "5", "1", typename, keytype, "", "", "", "", "", "", "", "", page + "");
            }
        });
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case BLOG_LIST:
            case CUSTOM_BLOG_COUNT:
            case BLOGTYPE_LIST:
            case BLOG_SAVEOPERATE:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case BLOG_LIST:
            case CUSTOM_BLOG_COUNT:
            case BLOGTYPE_LIST:
            case BLOG_SAVEOPERATE:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case CUSTOM_BLOG_COUNT:
                HemaArrayResult<CustomCount> cResult = (HemaArrayResult<CustomCount>) baseResult;
                if (cResult != null) {
                    CustomCount count = cResult.getObjects().get(0);
                    tvSaleCount.setText(count.getOnsale_count());
                    tvWarehouseCount.setText(count.getLeftcount());
                }
                break;
            case BLOG_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                if ("0".equals(page)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    refreshLoadmoreLayout.setLoadmoreable(true);
                    mDatas.clear();
                    mDatas.addAll(bResult.getObjects());
                } else {//加载更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (bResult.getObjects().size() > 0) {
                        mDatas.addAll(bResult.getObjects());
                    } else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshDatas(-1);
                break;
            case BLOGTYPE_LIST:
                HemaArrayResult<BlogType> typeResult = (HemaArrayResult<BlogType>) baseResult;
                if (typeResult == null || typeResult.getObjects() == null)
                    return;
                types.clear();
                BlogType type = new BlogType();
                type.setName("全部");
                types.add(type);
                types.addAll(typeResult.getObjects());
                break;
            case BLOG_SAVEOPERATE:
                refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case BLOGTYPE_LIST:
                XtomToastUtil.showShortToast(mContext, "获取分类失败," + baseResult.getMsg());
                break;
            case CUSTOM_BLOG_COUNT:
                XtomToastUtil.showShortToast(mContext, "获取信息失败" + baseResult.getMsg());
                break;
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败" + baseResult.getMsg());
                break;
            case BLOG_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("4"))
                    XtomToastUtil.showShortToast(mContext, "删除失败" + baseResult.getMsg());
                else if (keytype.equals("5"))
                    XtomToastUtil.showShortToast(mContext, "下架失败" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case BLOGTYPE_LIST:
                XtomToastUtil.showShortToast(mContext, "获取分类失败,请稍后再试");
                break;
            case CUSTOM_BLOG_COUNT:
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                break;
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    refreshLoadmoreLayout.refreshFailed();
                } else {
                    refreshLoadmoreLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                refreshDatas(failedType);
                break;
            case BLOG_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("4"))
                    XtomToastUtil.showShortToast(mContext, "删除失败，请稍后再试");
                else if (keytype.equals("5"))
                    XtomToastUtil.showShortToast(mContext, "下架失败，请稍后再试");
                break;
        }
    }

    private void refreshDatas(final int failedType) {
        if (adapter == null) {
            adapter = new BlogSelectAdapter2(mContext, mDatas);
            adapter.setType(1);
            adapter.setClickListener(new OnItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    int type = adapter.getType();
                    if (type == 1) {
                        Intent intent = new Intent(mContext, FarmerCropDetailActivity.class);
                        intent.putExtra("blog_id", mDatas.get(position).getId());
                        startActivity(intent);
                    }else {
                        Blog selectBlog = mDatas.get(position);
                        if (selectBlog.isCheck())
                            selectBlog.setCheck(false);
                        else
                            selectBlog.setCheck(true);
                        adapter.notifyDataSetChanged();
                        isAllChecked = checkAllSelected();
                        ckbxAll.setChecked(isAllChecked);
                    }
                }
            });
            adapter.setEmptyString("暂无商品");
            listview.setAdapter(adapter);
        } else
            adapter.notifyDataSetChanged();
        adapter.setFailtype(failedType);

    }

    @OnClick({R.id.title_left_btn, R.id.title_right_btn, R.id.layout_sale,
            R.id.layout_warehouse, R.id.tv_new, R.id.tv_manager, R.id.tv_delete,
            R.id.tv_off_shelf, R.id.tv_assort, R.id.ckbx_all})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_btn:
                adapter.setType(1);
                adapter.notifyDataSetChanged();
                titleRightBtn.setVisibility(View.GONE);
                layoutManager.setVisibility(View.GONE);
                tvManager.setVisibility(View.VISIBLE);
                break;
            case R.id.layout_sale:
                lineSales.setVisibility(View.VISIBLE);
                lineWarehouse.setVisibility(View.GONE);
                tvOffShelf.setVisibility(View.VISIBLE);
                lineManager.setVisibility(View.VISIBLE);
                keytype = "1";
                page = 0;
                getNetWorker().blogList("3", user.getId(), "5", "1", typename, keytype, "", "", "", "", "", "", "", "", page + "");
                isAllChecked = false;
                ckbxAll.setChecked(false);
                break;
            case R.id.layout_warehouse:
                lineSales.setVisibility(View.GONE);
                lineWarehouse.setVisibility(View.VISIBLE);
                tvOffShelf.setVisibility(View.GONE);
                lineManager.setVisibility(View.GONE);
                keytype = "0";
                page = 0;
                getNetWorker().blogList("3", user.getId(), "5", "1", typename, keytype, "", "", "", "", "", "", "", "", page + "");
                isAllChecked = false;
                ckbxAll.setChecked(false);
                break;
            case R.id.tv_assort:
                if (mPopupWindow == null)
                    initPopuptWindow();
                mPopupWindow.showAsDropDown(tvAssort);
                break;
            case R.id.tv_new:
                Intent itNew = new Intent(mContext, ReleaseGoodsActivity.class);
                itNew.putExtra("blog_id", "无");
                startActivity(itNew);
                break;
            case R.id.tv_manager:
                titleRightBtn.setVisibility(View.VISIBLE);
                layoutManager.setVisibility(View.VISIBLE);
                tvManager.setVisibility(View.GONE);
                adapter.setType(2);
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_delete:
                if (!hasSelected()) {
                    XtomToastUtil.showShortToast(mContext, "请至少选择一件商品");
                    return;
                }
                HemaButtonDialog dialog1 = new HemaButtonDialog(mContext);
                dialog1.setText("确定删除这些商品？");
                dialog1.setRightButtonText("确定");
                dialog1.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                dialog1.setLeftButtonText("取消");
                dialog1.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        String ids = "";
                        for (Blog blog : mDatas) {
                            if (blog.isCheck()) {
                                ids = ids + blog.getId() + ",";
                            }
                        }
                        if (ids.length() > 0)
                            ids = ids.substring(0, ids.length() - 1);
                        getNetWorker().blogSaveoperate(user.getToken(), "1", ids);
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.tv_off_shelf:
                if (!hasSelected()) {
                    XtomToastUtil.showShortToast(mContext, "请至少选择一件商品");
                    return;
                }
                HemaButtonDialog dialog2 = new HemaButtonDialog(mContext);
                dialog2.setText("确定将这些商品下架？");
                dialog2.setRightButtonText("确定");
                dialog2.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                dialog2.setLeftButtonText("取消");
                dialog2.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                    @Override
                    public void onRightButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                        String ids = "";
                        for (Blog blog : mDatas) {
                            if (blog.isCheck()) {
                                ids = ids + blog.getId() + ",";
                            }
                        }
                        if (ids.length() > 0)
                            ids = ids.substring(0, ids.length() - 1);
                        getNetWorker().blogSaveoperate(user.getToken(), "2", ids);
                    }

                    @Override
                    public void onLeftButtonClick(HemaButtonDialog dialog) {
                        dialog.cancel();
                    }
                });
                break;
            case R.id.ckbx_all:
                isAllChecked = !isAllChecked;
                for (Blog item: mDatas) {
                    item.setCheck(isAllChecked);
                }
                adapter.notifyDataSetChanged();
//                Log.d("uu", "ckbxAll:"+ckbxAll.isChecked());
                ckbxAll.setChecked(isAllChecked);
                break;
        }
    }

    /**判断是否已经全选
     * @return
     */
    private boolean checkAllSelected() {
        boolean allCheck = true;
        for (Blog blog : mDatas) {
            if (!blog.isCheck()) {
                allCheck = false;
                break;
            }
        }
        return allCheck;
    }

    /**
     * 判断是否已经选择内容
     *
     * @return true是，false一个都没选
     */
    private boolean hasSelected() {
        boolean has = false;
        for (Blog item : mDatas) {
            if (item.isCheck()) {
                has = true;
                break;
            }
        }
        return has;
    }

    private void initPopuptWindow() {
        final View popView = getLayoutInflater().inflate(R.layout.pop_blog_assort, null);
        final ListView listView = (ListView) popView.findViewById(R.id.listview);
        int width = tvAssort.getWidth();
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) listView.getLayoutParams();
        params.width = width;
        params.gravity = Gravity.RIGHT;
        listView.setAdapter(new AssortAdapter());

        mPopupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        popView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int top = listView.getTop();
                int wide = listView.getLeft();
                int bottom = listView.getBottom();
                int y = (int) event.getY();
                int x = (int) event.getX();
                if (x < wide || y < top || y > bottom) {
                    mPopupWindow.dismiss();
                }
                return true;
            }
        });
    }

    class AssortAdapter extends BaseAdapter {

        public AssortAdapter() {

        }

        @Override
        public int getCount() {
            return types.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_pop_blog_assort2, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(R.id.TAG_VIEWHOLDER, holder);
            } else
                holder = (ViewHolder) convertView.getTag(R.id.TAG_VIEWHOLDER);
            holder.setData(position);
            return convertView;
        }

        class ViewHolder {
            @Bind(R.id.tv_assort)
            TextView tvAssort;
            int position;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (position == 0)
                            typename = "";
                        else
                            typename = tvAssort.getText().toString();
                        mPopupWindow.dismiss();
                        refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
                    }
                });
            }

            private void setData(int position) {
                this.position = position;
                tvAssort.setText(types.get(position).getName());
            }
        }
    }


    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.NEW_GOODS) {
            refreshLoadmoreLayout.getOnStartListener().onStartRefresh(refreshLoadmoreLayout);
        }
    }
}
